import 'package:flutter/material.dart';
import 'package:wallpaper/pages/navbar/child/mobile_list.dart';

class MobilePage extends StatefulWidget {
  const MobilePage({super.key});

  @override
  State<MobilePage> createState() => _MobilePageState();
}

class _MobilePageState extends State<MobilePage> with TickerProviderStateMixin {
  late TabController _tabController; // 声明 TabController
  final PageController _pageController = PageController(); // 添加这行
  final List<String> _subList = ['最新', '最热']; // Tab 标签列表

  @override
  void initState() {
    // 初始化时获取数据 等待页面渲染完成
    WidgetsBinding.instance.addPostFrameCallback((_) {});
    super.initState();
    // 初始化 TabController
    _tabController = TabController(
      length: _subList.length,
      vsync: this,
    );
  }

  @override
  void dispose() {
    _tabController.dispose(); // 销毁控制器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 页面内容列表
    final List<Widget> pages = [
      MobileList(order: 'new'),
      MobileList(order: 'hot'),
    ];

    return Scaffold(
      appBar: AppBar(
        title: const Text(''),
        toolbarHeight: 0, // 恢复默认高度
        elevation: 0,
        backgroundColor: Theme.of(context).colorScheme.primaryContainer,
        bottom: TabBar(
          physics: const ClampingScrollPhysics(), // 滚动边界回弹效果
          controller: _tabController,
          indicatorPadding: EdgeInsets.all(2),
          dividerHeight: 0, // 去除 TabBar 下方的分割线
          tabs: _subList.map((e) => Tab(text: e)).toList(),
          indicatorColor: Theme.of(context).colorScheme.primary, // 指示器颜色
          labelColor: Theme.of(context).colorScheme.primary, // 选中标签颜色
          unselectedLabelColor:
              Theme.of(context).colorScheme.onSurface, // 未选中标签颜色
          onTap: (index) {
            // 点击 Tab 时切换页面
            _pageController.animateToPage(
              index,
              duration: const Duration(milliseconds: 300),
              curve: Curves.ease,
            );
          },
        ),
      ),
      body: PageView(
        controller: _pageController,
        children: pages,
        onPageChanged: (index) {
          // 页面滑动时同步 Tab
          _tabController.animateTo(index);
        },
      ),
    );
  }
}
